<template>
    <el-drawer :model-value="transportStore.isDrawerVisible" direction="rtl" size="75%"
        @close="transportStore.hideDrawer()" :with-header="false">
        <div class="transport-drawer-header">
            <h3>传输列表</h3>
            <div class="transport-summary">
                <a href="#" :class="{ active: activeFilter === 'all' }" @click.prevent="activeFilter = 'all'">
                    全部({{ summary.total }})
                </a>
                <a href="#" :class="{ active: activeFilter === 'uploading' }"
                    @click.prevent="activeFilter = 'uploading'">
                    上传中({{ summary.uploading }})
                </a>
                <a href="#" :class="{ active: activeFilter === 'queuing' }" @click.prevent="activeFilter = 'queuing'">
                    排队中({{ summary.queuing }})
                </a>
                <a href="#" :class="{ active: activeFilter === 'success' }" @click.prevent="activeFilter = 'success'">
                    已成功({{ summary.success }})
                </a>
                <a href="#" :class="{ active: activeFilter === 'failed' }" @click.prevent="activeFilter = 'failed'">
                    已失败({{ summary.failed }})
                </a>
            </div>
            <div class="transport-actions">
                <el-button type="success" plain size="small" @click="transportStore.resumeAllTasks()">
                    全部继续
                </el-button>
                <el-button type="primary" plain size="small" @click="transportStore.clearCompleted()">清除已完成</el-button>
                <el-button type="warning" plain size="small" @click="transportStore.pauseAllTasks()">全部暂停</el-button>
                <el-button type="danger" plain size="small" @click="transportStore.cancelAllTasks()">全部取消</el-button>
                <el-button type="info" plain size="small" @click="transportStore.clearAllTasks()">清除全部</el-button>
            </div>
        </div>

        <el-table :data="filteredTransportList" style="width: 100%" height="calc(100vh - 150px)" row-key="id"
            :row-class-name="tableRowClassName" :expand-row-keys="expandedRows" @expand-change="handleExpandChange">

            <el-table-column type="expand">
                <template #default="props">
                    <el-table :data="props.row.multipart?.chunks" style="width: 100%" size="small" border
                        row-key="chunkId">
                        <el-table-column label="分片编号" prop="partNumber" width="100" align="center" />
                        <el-table-column label="状态" width="100" align="center">
                            <template #default="scope">
                                <el-tag :type="getChunkStatusTagType(scope.row.status)" size="small">{{
                                    scope.row.status }}</el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column label="进度">
                            <template #default="scope">
                                <el-progress v-if="scope.row.isLiveStream" :percentage="100" :indeterminate="true"
                                    status="success" :stroke-width="10" text-inside />
                                <el-progress v-else :percentage="Math.max(0, Math.min(scope.row.progress || 0, 100))"
                                    :stroke-width="10" text-inside />
                            </template>
                        </el-table-column>
                    </el-table>
                </template>
            </el-table-column>

            <!-- 1. 【文件】列：手动使用 el-tooltip 来处理文件名 -->
            <el-table-column label="文件" min-width="200">
                <template #default="scope">
                    <div class="file-info-cell">
                        <el-tooltip effect="dark" :content="scope.row.name" placement="top" :show-after="500">
                            <div class="file-name-ellipsis">{{ scope.row.name }}</div>
                        </el-tooltip>
                        <div class="file-size">{{ scope.row.size === -1 ? '大小未知' : formatSize(scope.row.size) }}</div>
                    </div>
                </template>
            </el-table-column>

            <!-- 2. 【上传到】列：使用内置的 show-overflow-tooltip 属性处理目录 -->
            <el-table-column label="上传到" min-width="200" show-overflow-tooltip>
                <template #default="scope">
                    {{ getDisplayPath(scope.row) }}
                </template>
            </el-table-column>

            <!-- 其他列保持不变 -->
            <el-table-column label="状态" width="100">
                <template #default="scope">
                    <el-tag :type="getStatusTagType(scope.row.status)" size="small">{{ scope.row.status }}</el-tag>
                </template>
            </el-table-column>
            <el-table-column label="进度">
                <template #default="{ row: chunkRow }">
                    <!-- ========================================================= -->
                    <!-- == 【核心修复】确保分片进度条始终显示百分比文本        == -->
                    <!-- ========================================================= -->
                    <el-progress :percentage="chunkRow.progress || 0" :status="getChunkProgressStatus(chunkRow.status)">
                        <span>{{ chunkRow.progress || 0 }}%</span>
                    </el-progress>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="100"> <!-- 建议宽度调大一点 -->
                <!-- 在 TransportDrawer.vue 的“操作”列 -->
                <template #default="scope">
                    <div v-if="scope.row.isLiveStream">

                        <!-- 1a. 当任务正在传输时，显示“停止录制”按钮 -->
                        <el-button v-if="scope.row.status === '后台传输中'" type="danger" link
                            @click="transportStore.stopLiveStreamTask(scope.row.taskId)">
                            停止录制
                        </el-button>

                        <!-- 1b. 当任务正在停止过程中，显示文字提示 -->
                        <span v-else-if="scope.row.status === '正在停止...'" style="color: #E6A23C; font-size: 12px;">
                            {{ scope.row.status }}
                        </span>

                        <!-- 1c. 对于任何其他状态（如成功、失败、已停止），显示“清除记录” -->
                        <el-button v-else link type="danger" @click="transportStore.removeTask(scope.row.id)">
                            清除记录
                        </el-button>

                    </div>

                    <!-- 2. 如果是普通上传/分片上传任务 (您原来的逻辑) -->
                    <div v-else>
                        <template v-if="['上传中', '初始化...', '排队中', '合并中...', '后台传输中'].includes(scope.row.status)">
                            <div class="action-buttons">
                                <el-button type="primary" link @click="transportStore.pauseTask(scope.row.id)"
                                    :disabled="scope.row.uploadMode === 'url_transfer'">
                                    暂停
                                </el-button>
                                <el-button type="danger" link @click="transportStore.cancelTask(scope.row.id)">
                                    取消
                                </el-button>
                            </div>
                        </template>

                        <template v-else-if="['已暂停', '已中断'].includes(scope.row.status)">
                            <div class="action-buttons">
                                <el-button type="primary" link
                                    @click="transportStore.resumeTask(scope.row.id)">继续</el-button>
                                <el-button type="danger" link
                                    @click="transportStore.cancelTask(scope.row.id)">取消</el-button>
                            </div>
                        </template>

                        <el-button v-else link type="danger" @click="transportStore.removeTask(scope.row.id)">
                            清除记录
                        </el-button>
                    </div>
                </template>
            </el-table-column>
        </el-table>
    </el-drawer>
</template>

<script setup>
import { ref, computed } from 'vue';
import { useTransportStore } from '@/stores';

const expandedRows = ref([]);
const handleExpandChange = (row, expandedRowsData) => {
    // expandedRowsData 是 Element Plus 传递的当前所有已展开行的完整数据数组
    // 我们只需要提取出它们的 id 即可
    if (expandedRowsData.length > 0) {
        // 为了实现“手风琴”效果（一次只展开一个），我们只取最后一个被展开的行
        const lastExpandedRow = expandedRowsData[expandedRowsData.length - 1];
        expandedRows.value = [lastExpandedRow.id];
    } else {
        // 如果没有展开的行，就清空数组
        expandedRows.value = [];
    }
};

const formatSize = (bytes) => {
    if (bytes === 0) return '0 Bytes';
    const k = 1024;
    const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
};

const transportStore = useTransportStore();
const summary = computed(() => transportStore.summary);

// const reversedTransportList = computed(() => {
//     // 使用 slice() 创建一个浅拷贝，然后 reverse()，这不会修改原始的 store state
//     return [...transportStore.transportList].reverse();
// });

const activeFilter = ref('all'); // 'all', 'uploading', 'success', 'failed'

const sortedList = computed(() => {
    const statusPriority = {
        '初始化...': 1, '上传中': 1, '合并中...': 1, '正在停止...': 1, '后台传输中': 1,
        '排队中': 2,
        '已暂停': 3, '已中断': 3,
        '失败': 4, '已取消': 4,
        '成功': 5,
    };
    return [...transportStore.transportList].sort((a, b) => {
        const priorityA = statusPriority[a.status] || 99;
        const priorityB = statusPriority[b.status] || 99;
        return priorityA - priorityB;
    });
});

const filteredTransportList = computed(() => {
    // 不再需要 .reverse()，因为 sortedList 已经按优先级排好了
    const listToFilter = sortedList.value;

    if (activeFilter.value === 'all') {
        return listToFilter;
    }
    if (activeFilter.value === 'uploading') {
        return listToFilter.filter(t => ['上传中', '合并中...', '初始化...', '后台传输中', '正在停止...'].includes(t.status));
    }
    if (activeFilter.value === 'queuing') {
        return listToFilter.filter(t => t.status === '排队中');
    }
    if (activeFilter.value === 'success') {
        return listToFilter.filter(t => t.status === '成功');
    }
    if (activeFilter.value === 'failed') {
        return listToFilter.filter(t => ['失败', '已取消', '已中断'].includes(t.status));
    }
    return listToFilter;
});

const getStatusTagType = (status) => {
    switch (status) {
        case '上传中':
        case '合并中...':
        case '初始化...':
            return 'primary'; // <-- 【修正】明确返回 'primary'，代表蓝色
        case '成功':
            return 'success';
        case '失败':
            return 'danger';
        case '已取消':
            return 'warning';
        case '已中断':
            return 'info';
        default: // 排队中
            return 'info';
    }
};

const getChunkStatusTagType = (status) => {
    // 【核心修正】使用 if 语句和 startsWith() 来处理动态的状态文本
    if (status === '成功') {
        return 'success'; // 绿色
    }
    if (status === '上传中') {
        return 'primary'; // 蓝色
    }
    if (status.startsWith('重试中')) { // <-- 这里是关键！
        return 'warning'; // 黄色
    }
    if (status === '失败') {
        return 'danger'; // 红色
    }
    if (status === '已取消' || status === '已暂停') {
        return 'warning'; // 黄色
    }
    // 其他所有状态（排队中, 待恢复, 初始化...）都用灰色
    return 'info'; // 灰色
};

const getDisplayPath = (task) => {
    // 1. 将 bucketName 和 basePath 安全地拼接在一起
    //    (task.basePath || '') 确保在 basePath 不存在时不会出错
    let fullPath = `${task.bucketName}/${task.basePath || ''}`;

    // 2. 使用正则表达式，将连续的多个斜杠替换为单个斜杠
    fullPath = fullPath.replace(/\/+/g, '/');

    // 3. 确保路径以单个斜杠结尾（如果它不是只有 bucketName）
    if (task.basePath) {
        if (!fullPath.endsWith('/')) {
            fullPath += '/';
        }
    }

    return fullPath;
};

const getChunkProgressStatus = (status) => {
    const map = { '成功': 'success', '失败': 'exception', '已暂停': 'warning' };
    return map[status];
};

const tableRowClassName = ({ row }) => {
    if (row.uploadMode === 'multipart') {
        return 'is-multipart';
    }
    return '';
};
</script>

<style scoped>
.transport-drawer-header {
    padding: 0 20px 10px 20px;
    border-bottom: 1px solid var(--el-border-color-lighter);
}

.transport-drawer-header h3 {
    margin: 0 0 10px 0;
}

.transport-summary {
    display: flex;
    gap: 15px;
    font-size: 14px;
    color: #606266;
    margin-bottom: 10px;
}

.transport-actions {
    display: flex;
    justify-content: flex-end;
    /* 让内容靠右对齐 */
    align-items: center;
    gap: 16px;
    /* 在按钮组和“清除已完成”之间创建间距 */
}

.file-info-cell {
    line-height: 1.4;
    /* 调整行高，让两行文字不那么挤 */
}

.file-name {
    /* 文件名样式可以不加，使用默认的即可 */
    color: var(--el-text-color-primary);
}

.file-size {
    font-size: 12px;
    /* 字体小一点 */
    color: #909399;
    /* 灰色字体 */
}

.file-name-ellipsis {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.chunk-details-container {
    padding: 10px 20px 10px 50px;
    /* 左侧增加内边距，与主行对齐 */
    background-color: #f5f7fa;
}

:deep(.el-table__row:not(.is-multipart) .el-table__expand-icon) {
    display: none;
}

.transport-summary a {
    text-decoration: none;
    color: #606266;
    padding: 4px 8px;
    border-radius: 4px;
    transition: all 0.2s ease-in-out;
}

.transport-summary a:hover {
    background-color: #f5f7fa;
}

.transport-summary a.active {
    color: var(--el-color-primary);
    background-color: var(--el-color-primary-light-9);
    font-weight: 500;
}

.action-buttons {
    display: flex;
    /* 1. 使用 Flexbox 布局 */
    align-items: center;
    /* 2. 垂直居中 (可选，但推荐) */
    justify-content: flex-start;
    /* 3. 水平方向从左到右排列 */
    gap: 8px;
    /* 4. 在按钮之间创建一个 8px 的间隙 */
}

/* 确保 link 类型的按钮在 flex 容器中表现正常 */
.action-buttons .el-button--link {
    padding-left: 0;
    padding-right: 0;
}
</style>